// 此文件运行在 Node.js 服务器上
import { createSSRApp } from 'vue';
// Vue 的服务端渲染 API 位于 `vue/server-renderer` 路径下
import { renderToString } from 'vue/server-renderer';
import http from 'http';
import path from 'path';
import fs from 'fs';
import url from 'url';

const server = http.createServer((req, res) => {
  if (req.url === '/client.js') {
    // node 10.12之后__dirname不再是全局变量,需要通过
    const dirname = path.dirname(url.fileURLToPath(import.meta.url));
    console.log('dirname', dirname);
    const filePath = path.join(dirname, './client.js');

    fs.readFile(filePath, 'utf-8', (err, data) => {
      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('Not Found');
      } else {
        res.writeHead(200, { 'Content-Type': 'application/javascript' });
        res.end(data);
      }
    });
  }
  if (req.url === '/') {
    const app = createSSRApp({
      data() {
        return { count: 1 };
      },
      template: `<button @click="count++">{{ count }}</button>`
    });

    renderToString(app).then((html) => {
      console.log(html);
      // "vue": "https://cdn.jsdelivr.net/npm/vue@3.3.11/dist/vue.global.min.js",
      // https://unpkg.com/vue@3.0.0-rc.10/dist/vue.esm-browser.js
      // "vue": "https://unpkg.com/vue@3/dist/vue.esm-browser.js"
      // "vue": "https://cdn.jsdelivr.net/npm/vue@3.3.11/+esm",
      res.end(`
      <!DOCTYPE html>
    <html>
      <head>
        <title>Vue SSR Example</title>
        <script type="importmap">
        {
          "imports": {
            "vue": "https://cdn.jsdelivr.net/npm/vue@3/dist/vue.esm-browser.js"
          }
        }
        </script>
        <script type="module" src="/client.js"></script>
      </head>
      <body>
        <div id="app">${html}</div>
      </body>
    </html>`);
    });
  }
});
server.listen(3000, () => {
  console.log('Server is running at localhost:3000');
});
